<template>
  <div>
    <!-- 头部导航栏 -->
    <nav class="navbar" style="position: relative">

      <div class="logo" >
        <span style="font-weight: bold; margin: 0; line-height: 1; font-size: 1rem">ndnu-教科研管理系统</span>
        <span style="font-weight: normal; margin: 0; line-height: 1.5; font-size: 0.8rem">Achievement Management System</span>
      </div>

      <ul class="nav-links">
        <li><router-link :class="{ active: isActive('/home') }">首页</router-link></li>
        <li><router-link to="/main/result/papers" :class="{ active: isActive('/main/result') }">成果管理</router-link></li>
        <li><router-link to="/main/research/Longitudinal" :class="{ active: isActive('/main/research') }">课题管理</router-link></li>

        <li class="dropdown">
          <a href="#" @click.prevent="toggleDropdown" :class="{ active: isActive('/contact') }">
            学术助手
          </a>
          <ul class="dropdown-menu" v-show="showDropdown">
            <li><router-link to="/academic/generate">生成材料</router-link></li>
            <li><router-link to="/main/table">汇总表格</router-link></li>
            <li><router-link to="/academic/solution">结题助手</router-link></li>
          </ul>
        </li>
      </ul>

      <!-- 上传新增按钮和下拉菜单 -->
      <div class="upload-container">
        <button @click="toggleUploadDropdown" class="upload-button">上传新增</button>
        <ul class="upload-dropdown-menu" v-show="showUploadDropdown">
          <li v-for="(option, index) in uploadOptions" :key="index">
            <router-link :to="option.path" @mouseover="hoverIndex = index" @mouseleave="hoverIndex = -1" :class="{ hover: hoverIndex === index }">
              {{ option.label }}
            </router-link>
          </li>
        </ul>
      </div>

      <!-- 头像部分 -->
      <div class="avatar-container">
        <img class="avatar" :src="userAvatar" alt="Avatar" @click="toggleAvatarDropdown" @error="handleAvatarError">
        <ul class="avatar-dropdown-menu" v-show="showAvatarDropdown">
          <li v-for="(option, index) in options" :key="index" @click="handleAvatarOption(option)">
            {{ option.label }}
          </li>
        </ul>
      </div>

      <!-- 优化后的退出确认对话框 -->
      <Transition name="fade">
        <div v-if="showConfirmation" class="modal-overlay" @click.self="cancelLogout">
          <div class="modal-content">
            <h2>确认退出</h2>
            <p>您确定要退出登录吗？</p>
            <div class="button-group">
              <button @click="confirmLogout" class="confirm-button">
                <span class="icon">✓</span> 确认
              </button>
              <button @click="cancelLogout" class="cancel-button">
                <span class="icon">✕</span> 取消
              </button>
            </div>
          </div>
        </div>
      </Transition>
    </nav>
    <router-view></router-view>
  </div>
</template>

<style scoped>
/* Enhanced navbar with gradient background and better shadows */
.navbar {
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08), 0 1px 3px rgba(0, 0, 0, 0.05);
  width: 100%;
  height: 4rem;
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgba(0, 179, 138, 0.1);
  backdrop-filter: blur(10px);
  position: sticky;
  top: 0;
  z-index: 100;
}

/* Enhanced logo with better typography and subtle animation */
.logo {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 0.5rem;
  margin-left: 20vw;
  transition: transform 0.3s ease;
}

.logo:hover {
  transform: translateY(-1px);
}

.logo span:first-child {
  margin: 0;
  line-height: 1;
  font-size: 1.1rem;
  font-weight: 700;
  background: linear-gradient(135deg, #00b38a, #00d4aa);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.logo span:last-child {
  margin: 0;
  line-height: 1.5;
  font-size: 0.75rem;
  color: #64748b;
  font-weight: 500;
  letter-spacing: 0.5px;
}

/* Enhanced navigation links with better hover effects */
.nav-links {
  list-style: none;
  display: flex;
  padding: 0;
  margin: 0;
  margin-left: 7vw;
  position: relative;
}

.nav-links li {
  padding: 0 1.5rem;
  position: relative;
}

.nav-links a {
  position: relative;
  text-decoration: none;
  color: #64748b;
  font-weight: 600;
  font-size: 0.95rem;
  padding: 0.75rem 0;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  letter-spacing: 0.3px;
}

.nav-links a:hover {
  color: #00b38a;
  transform: translateY(-1px);
}

.nav-links a.active {
  color: #00b38a;
  font-weight: 700;
}

/* Enhanced underline animation with gradient */
.nav-links a::after {
  content: "";
  position: absolute;
  left: 50%;
  bottom: -0.5rem;
  width: 0;
  height: 3px;
  background: linear-gradient(90deg, #00b38a, #00d4aa);
  border-radius: 2px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  transform: translateX(-50%);
}

.nav-links a:hover::after,
.nav-links a.active::after {
  width: 100%;
}

/* Enhanced dropdown with better styling and animations */
.dropdown {
  position: relative;
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  left: 0;
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1), 0 4px 6px rgba(0, 0, 0, 0.05);
  border-radius: 12px;
  padding: 0.75rem 0;
  min-width: 160px;
  z-index: 1000;
  margin-top: 0.75rem;
  border: 1px solid rgba(0, 179, 138, 0.1);
  backdrop-filter: blur(10px);
  animation: slideDown 0.3s ease;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.dropdown-menu li {
  padding: 0;
}

.dropdown-menu a {
  display: block;
  padding: 0.75rem 1.25rem;
  color: #64748b;
  text-decoration: none;
  font-size: 0.9rem;
  font-weight: 500;
  transition: all 0.2s ease;
  border-radius: 8px;
  margin: 0 0.5rem;
}

.dropdown-menu a:hover {
  background: linear-gradient(135deg, #00b38a, #00d4aa);
  color: white;
  transform: translateX(4px);
}

.dropdown-menu a::after {
  display: none;
}

/* Enhanced avatar with better styling and hover effects */
.avatar-container {
  position: relative;
  margin-left: 1.5rem;
}

.avatar {
  width: 48px;
  height: 48px;
  overflow: hidden;
  border-radius: 50%;
  border: 3px solid transparent;
  background: linear-gradient(white, white) padding-box,
  linear-gradient(135deg, #00b38a, #00d4aa) border-box;
  box-shadow: 0 4px 15px rgba(0, 179, 138, 0.2);
  cursor: pointer;
  margin-top: 5px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.avatar:hover {
  transform: translateY(-2px) scale(1.05);
  box-shadow: 0 8px 25px rgba(0, 179, 138, 0.3);
}

.avatar img {
  width: 100%;
  height: auto;
  display: block;
}

/* Enhanced avatar dropdown with better styling */
.avatar-dropdown-menu {
  position: absolute;
  top: 100%;
  right: 0;
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1), 0 4px 6px rgba(0, 0, 0, 0.05);
  border-radius: 12px;
  padding: 0.75rem 0;
  min-width: 140px;
  z-index: 1000;
  margin-top: 0.75rem;
  border: 1px solid rgba(0, 179, 138, 0.1);
  animation: slideDown 0.3s ease;
}

.avatar-dropdown-menu li {
  padding: 0.5rem 1.25rem;
  cursor: pointer;
  font-weight: 500;
  color: #64748b;
  transition: all 0.2s ease;
  margin: 0 0.5rem;
  border-radius: 8px;
}

.avatar-dropdown-menu li:hover {
  background: linear-gradient(135deg, #00b38a, #00d4aa);
  color: white;
  transform: translateX(4px);
}

/* Enhanced upload container with modern button styling */
.upload-container {
  position: relative;
  margin-left: 10rem;
}

.upload-button {
  background: linear-gradient(135deg, #00b38a, #00d4aa);
  color: white;
  font-weight: 600;
  cursor: pointer;
  border: none;
  width: 7rem;
  letter-spacing: 0.5px;
  height: 2.75rem;
  font-size: 0.85rem;
  border-radius: 12px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 4px 15px rgba(0, 179, 138, 0.3);
  position: relative;
  overflow: hidden;
}

.upload-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.upload-button:hover::before {
  left: 100%;
}

.upload-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 179, 138, 0.4);
}

.upload-button:active {
  transform: translateY(0);
}

/* Enhanced upload dropdown with better styling */
.upload-dropdown-menu {
  position: absolute;
  top: 100%;
  left: 0;
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1), 0 4px 6px rgba(0, 0, 0, 0.05);
  border-radius: 12px;
  padding: 0.75rem 0;
  min-width: 180px;
  z-index: 1000;
  margin-top: 0.75rem;
  list-style: none;
  border: 1px solid rgba(0, 179, 138, 0.1);
  max-height: 400px;
  overflow-y: auto;
  animation: slideDown 0.3s ease;
}

.upload-dropdown-menu::-webkit-scrollbar {
  width: 6px;
}

.upload-dropdown-menu::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 3px;
}

.upload-dropdown-menu::-webkit-scrollbar-thumb {
  background: linear-gradient(135deg, #00b38a, #00d4aa);
  border-radius: 3px;
}

.upload-dropdown-menu li {
  padding: 0;
}

.upload-dropdown-menu a {
  display: block;
  padding: 0.75rem 1.25rem;
  color: #64748b;
  text-decoration: none;
  font-size: 0.9rem;
  font-weight: 500;
  transition: all 0.2s ease;
  border-radius: 8px;
  margin: 0 0.5rem;
}

.upload-dropdown-menu a:hover,
.upload-dropdown-menu a.hover {
  background: linear-gradient(135deg, #00b38a, #00d4aa);
  color: white;
  transform: translateX(4px);
}

/* Enhanced modal with better backdrop and animations */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.6);
  backdrop-filter: blur(8px);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.modal-content {
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  padding: 2.5rem;
  border-radius: 20px;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.2);
  text-align: center;
  max-width: 420px;
  width: 90%;
  border: 1px solid rgba(0, 179, 138, 0.1);
  animation: modalSlideIn 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.modal-content h2 {
  margin-top: 0;
  color: #1e293b;
  font-size: 1.5rem;
  margin-bottom: 1rem;
  font-weight: 700;
}

.modal-content p {
  margin-bottom: 2rem;
  color: #64748b;
  font-size: 1rem;
  line-height: 1.6;
}

/* Enhanced button group with better spacing and styling */
.button-group {
  display: flex;
  justify-content: center;
  gap: 1rem;
}

.confirm-button,
.cancel-button {
  padding: 0.875rem 2rem;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  font-size: 0.95rem;
  font-weight: 600;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  display: flex;
  align-items: center;
  min-width: 120px;
  justify-content: center;
}

.confirm-button {
  background: linear-gradient(135deg, #00b38a, #00d4aa);
  color: white;
  box-shadow: 0 4px 15px rgba(0, 179, 138, 0.3);
}

.confirm-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 179, 138, 0.4);
}

.cancel-button {
  background: linear-gradient(135deg, #f1f5f9, #e2e8f0);
  color: #64748b;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.cancel-button:hover {
  background: linear-gradient(135deg, #e2e8f0, #cbd5e1);
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.icon {
  margin-right: 0.5rem;
  font-size: 1rem;
  font-weight: bold;
}

/* Enhanced fade transition */
.fade-enter-active, .fade-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
  transform: scale(0.95);
}

/* Enhanced responsive design with better mobile experience */
@media (max-width: 768px) {
  .navbar {
    height: auto;
    flex-direction: column;
    padding: 1.5rem;
    background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  }

  .logo {
    margin-bottom: 1.5rem;
    margin-left: 0;
  }

  .nav-links {
    flex-direction: column;
    margin-left: 0;
    width: 100%;
  }

  .nav-links li {
    padding: 0.75rem 0;
    text-align: center;
  }

  .upload-container {
    margin-left: 0;
    margin-top: 1.5rem;
  }

  .avatar-container {
    margin-left: 0;
    margin-top: 1.5rem;
  }

  .modal-content {
    padding: 2rem;
    margin: 1rem;
  }

  .button-group {
    flex-direction: column;
    gap: 0.75rem;
  }

  .confirm-button,
  .cancel-button {
    width: 100%;
  }
}

/* Additional smooth scrolling and focus styles */
* {
  scroll-behavior: smooth;
}

*:focus {
  outline: 2px solid rgba(0, 179, 138, 0.5);
  outline-offset: 2px;
}
</style>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import request from "@/utils/request";
import { ElMessage } from 'element-plus';
import { Bell } from '@element-plus/icons-vue';

const router = useRouter();
const route = useRoute();
const showDropdown = ref(false);
const showAvatarDropdown = ref(false);
const showUploadDropdown = ref(false);
const showNotification = ref(false);
const token = ref('');
const activeLink = ref('/');
const showConfirmation = ref(false);
const hoverIndex = ref(-1);
const userAvatar = ref('../../assets/头像.png'); // 默认头像

const options = reactive([
  { label: '个人信息' },
  { label: '退出登录' }
]);

const uploadOptions = reactive([
  { label: '纵向课题', path: '/main/add/longitudinal' },
  { label: '横向课题', path: '/main/add/horizontal' },
  { label: '论文', path: '/main/add/papers' },
  { label: '专利', path: '/main/add/patents' },
  { label: '软件著作权', path: '/main/add/software' },
  { label: '个人获奖', path: '/main/add/Personal/Award' },
  { label: '学生获奖', path: '/main/add/Student/Award' },
  { label: '继续教育材料', path: '/main/add/ContinueEducation' },
  { label: '著作', path: '/main/add/Publication' },
  { label: '新闻报道', path: '/main/add/report' },
  { label: '档案资料', path: '/main/add/Certification' },
  { label: '其他', path: '/main/add/other' }
]);

const toggleDropdown = (event) => {
  event.stopPropagation();
  showDropdown.value = !showDropdown.value;
  showUploadDropdown.value = false;
  showAvatarDropdown.value = false;
  showNotification.value = false;
};

const toggleUploadDropdown = (event) => {
  event.stopPropagation();
  showUploadDropdown.value = !showUploadDropdown.value;
  showDropdown.value = false;
  showAvatarDropdown.value = false;
  showNotification.value = false;
};

const toggleAvatarDropdown = (event) => {
  event.stopPropagation();
  showAvatarDropdown.value = !showAvatarDropdown.value;
  showDropdown.value = false;
  showUploadDropdown.value = false;
  showNotification.value = false;
};

const toggleNotification = (event) => {
  event.stopPropagation();
  showNotification.value = !showNotification.value;
  showDropdown.value = false;
  showUploadDropdown.value = false;
  showAvatarDropdown.value = false;
};

const handleClickOutside = (event) => {
  const dropdown = document.querySelector('.dropdown');
  const uploadContainer = document.querySelector('.upload-container');
  const avatarContainer = document.querySelector('.avatar-container');
  const notificationContainer = document.querySelector('.notification-panel');
  const bellIcon = document.querySelector('.custom-icon-size');

  if (!dropdown?.contains(event.target) &&
      !uploadContainer?.contains(event.target) &&
      !avatarContainer?.contains(event.target) &&
      !notificationContainer?.contains(event.target) &&
      !bellIcon?.contains(event.target)) {
    showDropdown.value = false;
    showUploadDropdown.value = false;
    showAvatarDropdown.value = false;
    showNotification.value = false;
  }
};

const setActiveLink = (path) => {
  activeLink.value = path;
};

const isActive = (link) => {
  return activeLink.value.startsWith(link);
};

const showLogoutConfirmation = () => {
  showConfirmation.value = true;
  showAvatarDropdown.value = false;
};

const confirmLogout = () => {
  const user = localStorage.getItem("userInfo");
  const userObj = JSON.parse(user);

  if (!userObj || !userObj.token) {
    console.error('User object or token is missing.');
    return;
  }

  const logoutToken = userObj.token;
  const logoutRequest = {
    token: logoutToken
  };

  request.post('/user/logout', logoutRequest).then(response => {
    if (response.code === 1) {
      ElMessage.success('退出成功');
      setTimeout(() => {
        router.push('/');
      }, 500);
    } else {
      ElMessage.error(response.message || '退出失败，请重试');
    }
  }).catch(error => {
    console.log('请求错误:', error.response ? error.response.data : error);
    ElMessage.error('请求失败，请重试');
  });

  showConfirmation.value = false;
};

const cancelLogout = () => {
  showConfirmation.value = false;
};

const handlePersonal = () => {
  router.push("/personal");
};

const handleAvatarOption = (option) => {
  if (option.label === '个人信息') {
    handlePersonal();
  } else if (option.label === '退出登录') {
    showLogoutConfirmation();
  }
};

const getUserInfoFromStorage = () => {
  try {
    const userInfoStr = localStorage.getItem('userInfo');
    console.log('获取用户信息成功:', userInfoStr);
    if (userInfoStr) {
      const userInfo = JSON.parse(userInfoStr);
      if (userInfo.userAvatar) {
        userAvatar.value = userInfo.userAvatar;
      }
      token.value = userInfo.token;
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    ElMessage.error('获取用户信息失败');
  }
};

const handleAvatarError = () => {
  userAvatar.value = '../../assets/头像.png'; // 加载失败时使用默认头像
};

onMounted(() => {
  getUserInfoFromStorage();
  setActiveLink(route.path);
  document.addEventListener('click', handleClickOutside);
});

onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside);
});

watch(() => route.path, (newPath) => {
  setActiveLink(newPath);
});
</script>
